package com.ade.warehouse.controller;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.domain.Page;
import org.springframework.http.converter.json.MappingJacksonValue;
import org.springframework.web.bind.annotation.*;

import com.ade.warehouse.pojo.User;
import com.ade.warehouse.service.UserService;

import entity.PageResult;
import entity.Result;
import entity.StatusCode;
import util.CookieUtils;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 控制器层
 *
 * @author Administrator
 */
@RestController
@CrossOrigin
@RequestMapping("/user")
public class UserController {

    @Autowired
    private UserService userService;


    @Value("${TOKEN_KEY}")
    private String TOKEN_KEY;

    @RequestMapping(value = "/login", method = RequestMethod.POST)
    @ResponseBody
    public Result login(String username, String password,
                        HttpServletRequest request, HttpServletResponse response) {
        String token = userService.login(username, password);


        if (token == null) {
           return new Result(false, 1000, "用户名或者密码错误");
        }
        //添加到cookie中
        CookieUtils.setCookie(request, response, TOKEN_KEY, token);

        HashMap map = new HashMap<>();
        map.put(TOKEN_KEY, token);
        return new Result(true, StatusCode.OK, "登录成功", map);
    }


    @RequestMapping("/token/{token}")
    @ResponseBody
    public Object getUser(@PathVariable String token ,String callback) {
        //ajax不能进行直接跨域请求
        /*return tokenService.getUserByToken(token);*/
        Result userToken = userService.getUserByToken(token);
        if (StringUtils.isNotBlank(callback)) { //判断是否为jsonp请求
            //如果是，把结果封装成一个js语句响应（spring4.X以上版本写法）
            MappingJacksonValue mappingJacksonValue = new MappingJacksonValue(userToken);
            mappingJacksonValue.setJsonpFunction(callback);
            return mappingJacksonValue;
        }
        return userToken;
    }

    @RequestMapping("/token/edit")
    @ResponseBody
    public Object editUser(String token , User sysUser,String callback) {
        Result result = userService.editUserByToken(token, sysUser);
        if (StringUtils.isNotBlank(callback)) { //判断是否为jsonp请求
            //如果是，把结果封装成一个js语句响应（spring4.X以上版本写法）
            MappingJacksonValue mappingJacksonValue = new MappingJacksonValue(result);
            mappingJacksonValue.setJsonpFunction(callback);
            return mappingJacksonValue;
        }
        return result;
    }
    
    


    /**
     * 查询全部数据
     *
     * @return
     */
    @RequestMapping(method = RequestMethod.GET)
    public Result findAll() {
        return new Result(true, StatusCode.OK, "查询成功", userService.findAll());
    }

    /**
     * 根据ID查询
     *
     * @param id ID
     * @return
     */
    @RequestMapping(value = "/{id}", method = RequestMethod.GET)
    public Result findById(@PathVariable String id) {
        return new Result(true, StatusCode.OK, "查询成功", userService.findById(id));
    }


    /**
     * 分页+多条件查询
     *
     * @param searchMap 查询条件封装
     * @param page      页码
     * @param size      页大小
     * @return 分页结果
     */
    @RequestMapping(value = "/search/{page}/{size}", method = RequestMethod.POST)
    public Result findSearch(@RequestBody Map searchMap, @PathVariable int page, @PathVariable int size) {
        Page<User> pageList = userService.findSearch(searchMap, page, size);
        return new Result(true, StatusCode.OK, "查询成功", new PageResult<User>(pageList.getTotalElements(), pageList.getContent()));
    }

    /**
     * 根据条件查询
     *
     * @param searchMap
     * @return
     */
    @RequestMapping(value = "/search", method = RequestMethod.POST)
    public Result findSearch(@RequestBody Map searchMap) {
        return new Result(true, StatusCode.OK, "查询成功", userService.findSearch(searchMap));
    }

    /**
     * 增加
     *
     * @param user
     */
    @RequestMapping(method = RequestMethod.POST)
    public Result add(@RequestBody User user) {
        return new Result(userService.add(user), StatusCode.OK, "增加成功");
    }

    /**
     * 修改
     *
     * @param user
     */
    @RequestMapping(value = "/{id}", method = RequestMethod.PUT)
    public Result update(@RequestBody User user, @PathVariable String id) {
        user.setId(id);
        return new Result(userService.update(user), StatusCode.OK, "修改成功");
    }

    /**
     * 删除
     *
     * @param id
     */
    @RequestMapping(value = "/{id}", method = RequestMethod.DELETE)
    public Result delete(@PathVariable String id) {
        userService.deleteById(id);
        return new Result(true, StatusCode.OK, "删除成功");
    }

}
